/*
 * buzzer.c
 *
 *  Created on: Sep 19, 2013
 *      Author: Ken Arok
 */

#include "buzzer_hal.h"
#include "buzzer.h"

/* Function of turn off Buzzer. */
static TimerFuncVoid_t _funcTurnBuzzerOff;
/* Function of turn on Buzzer. */
static TimerFuncVoid_t _funcTurnBuzzerOn;
/* Timer for Buzzer OFF. */
static volatile uint32_t *_tmrBuzzerOff = NULL;
/* Timer for Buzzer On. */
static volatile uint32_t *_tmrBuzzerOn = NULL;

static uint8_t _buzzer_flag_on = 0, _buzzer_flag_off = 0;

/** \brief Turn Buzzer LCD ON.
 *
 *  \param _tmr	Pointer to obtained timer.
 *
 */
static void prvTurnOnBuzzer(void *_tmr);

/** \brief Turn Buzzer OFF.
 *
 *  \param _tmr	Pointer to obtained timer.
 *
 */
static void prvTurnOffBuzzer(void *_tmr);

/* ------------------------------------------------------------------------------ */

void vBuzzerSwitch(const uint8_t _on_off, uint32_t _val)
{
	switch(_on_off)
	{
		case iON:
			/* Turn Buzzer ON via Timer. */
			if(_tmrBuzzerOn == NULL) {
				/* Obtain Timer. */
				_tmrBuzzerOn = vTimer500msTake();
			}

			if(_tmrBuzzerOn != NULL) {
				if(_buzzer_flag_on < 2) {
					*_tmrBuzzerOn = _val;
				}

				if(_buzzer_flag_on == 0) {
					_buzzer_flag_on = 1;
					_funcTurnBuzzerOn = &prvTurnOnBuzzer;
					vTimer500msFuncReg(_funcTurnBuzzerOn, (void *)_tmrBuzzerOn);
				}
			}
		break;

		case iOFF:
			/* Turn Buzzer OFF via Timer. */
			if(_tmrBuzzerOff == NULL) {
				/* Obtain Timer. */
				_tmrBuzzerOff = vTimer500msTake();
			}

			if(_tmrBuzzerOff != NULL) {
				if(_buzzer_flag_off < 2) {
					*_tmrBuzzerOff = _val;
				}

				if (_buzzer_flag_off == 0) {
					_buzzer_flag_off = 1;
					_funcTurnBuzzerOff = &prvTurnOffBuzzer;
					vTimer500msFuncReg(_funcTurnBuzzerOff, (void *)_tmrBuzzerOff);
				}
			}
		break;

		default: break;
	}
}

/* -------------------------------------------------------------------------- */
static void prvTurnOnBuzzer(void *_tmr)
{
	uint32_t *_ptr = _tmr;

	if(*_ptr == 0) {
		_buzzer_flag_on = 2;
		/* Turn Buzzer On. */
		buzzer_on();
		/* Unregister the function from list. */
		vTimer500msFuncUnreg(_funcTurnBuzzerOn);
		/* Release Timers. */
		vTimer500msGive(_tmr);
	}
}

static void prvTurnOffBuzzer(void *_tmr)
{
	uint32_t *_ptr = _tmr;

	if(*_ptr == 0) {
		_buzzer_flag_off = 0;
		_buzzer_flag_on = 0;
		/* Turn Buzzer Off. */
		buzzer_off();
		/* Unregister the function from list. */
		vTimer500msFuncUnreg(_funcTurnBuzzerOff);
		/* Release Timers. */
		vTimer500msGive(_tmr);
	}
}

